import { ApiProperty } from '@nestjs/swagger'
import { Expose } from 'class-transformer'
import { IsNumber, IsOptional, IsString } from 'class-validator'
import {
  Column,
  CreateDateColumn,
  Entity,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm'
import { PlayerUser } from '@/modules/user/entities/player-user.entity'
import { WheelTask } from './wheel-task.entity'

/** 奖品表 */
@Entity('user_wheel_task')
export class UserWheelTask {
  @PrimaryGeneratedColumn()
  @IsNumber()
  userWheelTaskId: number

  /**
   * 关联用户UId
   */
  @Column()
  @IsString()
  userUid: string

  /**
   * 关联用户
   */
  @ManyToOne(() => PlayerUser, user => user.userTasks, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'userUid', referencedColumnName: 'uid' }) // 👈 指向非主键列 uid
  playerUser: PlayerUser

  /** 关联任务 */
  @ManyToOne(() => WheelTask, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'wheelTaskId' })
  wheelTask: WheelTask

  /**
   * 关联任务 ID
   */
  @Column()
  @IsString()
  wheelTaskId: number

  /**
   * 已经完成的次数
   */
  @Column({ default: 0 })
  @IsNumber()
  @IsOptional()
  completedCount?: number

  @CreateDateColumn()
  createdAt?: Date

  @UpdateDateColumn()
  updatedAt?: Date

  /** 剩余可完成次数 */
  @Expose()
  get remainingCount(): number {
    if (!this.wheelTask)
      return 0
    return Math.max(this.wheelTask.totalCompleteCount - this.completedCount, 0)
  }

  /** 是否完成 */
  @Expose()
  @ApiProperty({ readOnly: true })
  get isCompleted(): boolean {
    if (!this.wheelTask)
      return false
    return this.completedCount >= this.wheelTask.totalCompleteCount
  }
}
